//
//  ViewController.swift
//  NSTextViewNSTextField回车shift回车区分(swift)
//
//  Created by quanhao huang on 2019/12/20.
//  Copyright © 2019 quanhao huang. All rights reserved.
//

import Cocoa

class ViewController: NSViewController, NSTextFieldDelegate, NSTextViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    // MARK: - NSTextFieldDelegate
    func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        if commandSelector == #selector(insertNewline(_:)) {
            if let modifierFlags = NSApplication.shared.currentEvent?.modifierFlags, (modifierFlags.rawValue & NSEvent.ModifierFlags.shift.rawValue) != 0 {
                print("Shift-Enter detected.")
                textView.insertNewlineIgnoringFieldEditor(self)
                return true
            } else {
                print("Enter detected.")
            }
        }
        return false
    }
    
    // MARK: - NSTextViewDelegate
    func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
        if commandSelector == #selector(insertNewline(_:)) {
            if let modifierFlags = NSApplication.shared.currentEvent?.modifierFlags, (modifierFlags.rawValue & NSEvent.ModifierFlags.shift.rawValue) != 0 {
                print("Shift-Enter detected.")
                textView.insertNewlineIgnoringFieldEditor(self)
                return true
            } else {
                print("Enter detected.")
                return true
            }
        }
        return false
    }
    
}

